//
//  NewFeatureCollectionViewController.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/12.
//  Copyright © 2015年 余丽丽. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureCollectionViewController: UICollectionViewController {
    /// 图像总数
    private let imageCount = 4
    // MARK: - 构造函数
    /// 没有 override 说明 init 函数不是`指定`的构造函数
    /// 实现 init() 函数，可以保证外部调用的简单！
    init(){
        
        let layout = UICollectionViewFlowLayout()
        //设置属性
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
       

        
        super.init(collectionViewLayout: layout)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell

        // Configure the cell
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    /// 完成显示 cell - indexPath 是之前消失 cell 的 indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    
        let path = collectionView.indexPathsForVisibleItems().last!
        
        //判断是不是末尾
        if path.item == imageCount - 1{
        
        let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
        cell.startButtonAnim()
        }

    }

    }

   /// 新特性的 cell
    class NewFeatureCell: UICollectionViewCell {
       
        private var imageIndex: Int = 0 {
            didSet{
                iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
                 startButton.hidden = true
            }
        }
        
        // MARK: - 构造方法
        override init(frame: CGRect){
            super.init(frame: frame)
            
            prepareUI()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            
            prepareUI()
        }
        
        // 设置UI
        private func prepareUI(){
            contentView.addSubview(iconView)
            contentView.addSubview(startButton)
            
            //约束
            iconView.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
            
            startButton.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        }
        
        // 开始按钮
        @objc private func clickStartButton(){
            NSNotificationCenter.defaultCenter().postNotificationName(YLLRootViewControllerSwitchNotification, object: true)
        }
        
        /// 开始按钮动画效果
        private func startButtonAnim() {
        
            startButton.hidden = false
            startButton.transform = CGAffineTransformMakeScale(0, 0)
            // 禁用按钮操作
            startButton.userInteractionEnabled = false
            
            UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                
                // 恢复默认形变
                self.startButton.transform = CGAffineTransformIdentity
                
                }) { (_) -> Void in
                    // 启用按钮点击
                    self.startButton.userInteractionEnabled = true
            }

        
        }
        
        // MARK: - 懒加载控件
        private lazy var iconView = UIImageView()
        private lazy var startButton: UIButton = {
        
            let button = UIButton()
            
            button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
            button.setTitle("开始体验", forState: UIControlState.Normal)
            
            button.sizeToFit()
            
            // 提示: 按钮的隐藏属性会因为复用工作不正常
            button.hidden = true
            button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
            
            return button
        }()
    
    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
    
    }
    */

}
